// ignore_for_file: use_build_context_synchronously, avoid_print, prefer_typing_uninitialized_variables, deprecated_member_use
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:bot_toast/bot_toast.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper_app/components/AlertDialog/my_loading.dart';
import 'package:wallpaper_app/components/windows/window_title_bar.dart';
import 'package:wallpaper_app/tools/wallpaper_service.dart';

class LocalImage extends StatefulWidget {
  const LocalImage({super.key, required this.title});
  final String title;
  @override
  State<LocalImage> createState() => _LocalImageState();
}

class _LocalImageState extends State<LocalImage>
    with SingleTickerProviderStateMixin {
  String _selectedImagePath = "";
  var loadingBot;
  late AnimationController _controller;
  late Animation<double> _animation;
  late final theme = Theme.of(context).colorScheme;

  Future<void> _pickImage() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.image,
        allowMultiple: false,
      );

      if (result != null && result.files.isNotEmpty) {
        setState(() {
          _selectedImagePath = result.files.first.path ?? '';
        });
        _controller.forward(from: 0.0);
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择图片时出错: $e')),
      );
    }
  }

  void _setWallpaper() async {
    if (_selectedImagePath.isEmpty) {
      BotToast.showText(
        text: '请选择一张图片',
        contentColor: Colors.red,
        align: Alignment.center,
      );
      return;
    }

    loadingBot = BotToast.showCustomLoading(
        backgroundColor: const Color.fromARGB(100, 4, 4, 4),
        toastBuilder: (cancel) {
          return Container(
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: Colors.black54,
              borderRadius: BorderRadius.circular(15),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyLoading(type: 2),
                SizedBox(height: 15),
                Text(
                  '正在设置壁纸...',
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              ],
            ),
          );
        });
    try {
      await WallpaperService.setWallpaperInIsolate(_selectedImagePath);
    } catch (e) {
      print(e);
      loadingBot();
    }
  }

  void setupReceivePort() {
    final receivePort = ReceivePort();
    IsolateNameServer.registerPortWithName(receivePort.sendPort, 'mainPort');

    receivePort.listen((message) {
      if (message is Map) {
        final messageContent = message['message'];
        BotToast.showText(
          text: messageContent,
          align: Alignment.center,
          contentColor: theme.primary.withOpacity(0.8),
          textStyle: TextStyle(color: Colors.white, fontSize: 16),
        );
      }
      loadingBot();
    });
  }

  @override
  void initState() {
    super.initState();
    setupReceivePort();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    IsolateNameServer.removePortNameMapping('mainPort');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景层
          Positioned.fill(
            child: Container(
              color: Theme.of(context).scaffoldBackgroundColor,
            ),
          ),

          // 内容层
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题栏单独放置，不受模糊效果影响
              WindowTitleBar(isBack: true),

              // 内容区域
              Expanded(
                child: ClipRect(
                  // 裁剪确保模糊效果不会溢出到标题栏
                  child: _selectedImagePath.isEmpty
                      ? _buildEmptyState()
                      : _buildImagePreview(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildImagePreview() {
    return Stack(
      fit: StackFit.expand,
      children: [
        // 背景模糊效果 - 只应用于内容区域
        _selectedImagePath.isNotEmpty
            ? Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: FileImage(File(_selectedImagePath)),
                    fit: BoxFit.cover,
                  ),
                ),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 15, sigmaY: 15),
                  child: Container(
                    color: Colors.black.withOpacity(0.2),
                  ),
                ),
              )
            : SizedBox.shrink(),

        // 主要内容
        Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              Expanded(
                child: FadeTransition(
                  opacity: _animation,
                  child: Material(
                    elevation: 10,
                    type: MaterialType.transparency,
                    borderRadius: BorderRadius.circular(10),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: Image.file(
                        File(_selectedImagePath),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton.icon(
                    onPressed: _pickImage,
                    icon: Icon(Icons.refresh),
                    label: Text('重新选择'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: theme.surface,
                      foregroundColor: theme.primary,
                      padding:
                          EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                    ),
                  ),
                  SizedBox(width: 15),
                  ElevatedButton.icon(
                    onPressed: _setWallpaper,
                    icon: Icon(Icons.wallpaper, color: Colors.white),
                    label: Text('设置壁纸'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: theme.primary,
                      foregroundColor: Colors.white,
                      padding:
                          EdgeInsets.symmetric(horizontal: 25, vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Container(
      padding: EdgeInsets.all(20),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.wallpaper_rounded,
              size: 100,
              color: theme.primary.withOpacity(0.5),
            ),
            SizedBox(height: 20),
            Text(
              '选择本地图片设置为壁纸',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: theme.onSurface,
              ),
            ),
            SizedBox(height: 10),
            Text(
              '点击下方按钮选择您喜欢的图片',
              style: TextStyle(
                fontSize: 16,
                color: theme.onSurface.withOpacity(0.7),
              ),
            ),
            SizedBox(height: 30),
            ElevatedButton.icon(
              onPressed: _pickImage,
              icon: Icon(Icons.add_photo_alternate_outlined),
              label: Text('选择图片'),
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
